package com.ulook.lookplanet.util.json;

import com.ulook.lookplanet.util.ThrowException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Response;

/**
 * 描述：解析响应结果
 *
 * @author: L1998
 * @data: 2021/3/24
 */
public class ResponseParser {

    /**
     * 从响应结果中解析出data部分的字符串
     * @param response
     * @return
     */
    public static String parserData(Response response){

        String data = null;
        try {
            if (response.body() != null){
                String res = response.body().string();
                JSONObject jsonObject = new JSONObject(res);
                if("0".equals(jsonObject.getString("code"))){
                    data = jsonObject.getString("data");
                }
            }
        } catch (IOException e) {
            ThrowException.print(e, "响应结果不存在");
        } catch (JSONException e) {
            ThrowException.print(e, "解析失败");
        }
        return data;
    }

    /**
     * 从响应结果中解析出code部分的值
     * @param response
     * @return
     */
    public static String parserCode(Response response){

        String code = null;
        try {
            if (response.body() != null){
                String res = response.body().string();
                JSONObject jsonObject = new JSONObject(res);
                code = jsonObject.getString("data");
            }
        } catch (IOException e) {
            ThrowException.print(e, "响应结果不存在");
        } catch (JSONException e) {
            ThrowException.print(e, "解析失败");
        }
        return code;
    }

    /**
     * 从响应结果中解析出msg部分的值
     * @param response
     * @return
     */
    public static String parserMsg(Response response){

        String msg = null;
        try {
            if (response.body() != null){
                String res = response.body().string();
                JSONObject jsonObject = new JSONObject(res);
                msg = jsonObject.getString("data");
            }
        } catch (IOException e) {
            ThrowException.print(e, "响应结果不存在");
        } catch (JSONException e) {
            ThrowException.print(e, "解析失败");
        }
        return msg;
    }
}
